package com.my.socket.bio.v7;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by ZhongGang
 * at 2018/6/28 18:26
 */
public class SocketAccepter implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(SocketAccepter.class);

    private AtomicInteger startId;
    private ServerSocket serverSocket;
    private BlockingQueue<Connection> queue;

    public SocketAccepter(AtomicInteger startId, ServerSocket serverSocket, BlockingQueue<Connection> queue) {
        this.startId = startId;
        this.serverSocket = serverSocket;
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Socket socket = this.serverSocket.accept();
                Connection connection = new Connection(startId.incrementAndGet(), socket);
                LOGGER.info("thead: {}, incoming connection: {}", Thread.currentThread().getName(), connection);
                this.queue.put(connection);
            } catch (Exception e) {
                LOGGER.error("exception caught, the error is {}", e.getMessage());
                break;
            }
        }
    }
}
